package me.edzh.spring.bootstrap.utils;

import org.apache.http.util.TextUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collections;

public class StringUtils {
    public static boolean isEmpty(String str) {
        return str == null || str.isEmpty();
    }

    public static boolean isEmpty(String... strs) {
        if (strs == null) return true;

        for (String s : strs) {
            if (isEmpty(s)) return true;
        }

        return false;
    }

    public static String getMaskString(String str) {
        if (isEmpty(str)) return str;
        if (str.length() == 2) return "*" + str.charAt(1);
        if (str.length() == 1) return "*";

        StringBuilder sb = new StringBuilder(str.length());
        sb.append(str.charAt(0));
        for (int i = 1; i < str.length() - 1; ++i) {
            sb.append("*");
        }

        sb.append(str.charAt(str.length() - 1));

        return sb.toString();
    }

    public static int getHash(String string) {
        if (string == null) return 0;
        return string.hashCode();
    }

    public static String ifEmpty(String str, String defaultValue) {
        if (isEmpty(str)) {
            return defaultValue;
        }

        return str;
    }

    public static String ifNull(String str, String defaultValue) {
        if (null == str) {
            return defaultValue;
        }

        return str;
    }


    @NotNull
    public static String getMaskString(@Nullable String origin, int prefixLength, int paddingLength,
                                       int suffixLength, String paddingChar) {
        if (TextUtils.isEmpty(origin)) {
            return ""; // null | "" => ""
        }
        int length = origin.length();
        if (prefixLength + suffixLength > length) {
            return origin; // 非打码范围过大 返回源字符串
        }
        if (prefixLength < 0 || paddingLength < 0 || suffixLength < 0) {
            return origin; // 打码参数不正确 返回源字符串
        }
        String prefix = origin.substring(0, prefixLength);
        int suffixIndexBegin = length - suffixLength;
        String suffix = origin.substring(suffixIndexBegin);
        String padding = String.join("", Collections.nCopies(paddingLength, paddingChar));
        return prefix + padding + suffix;
    }

    @NotNull
    public static String getMaskString(@Nullable String origin, int prefixLength, int paddingLength,
                                       int suffixLength, char paddingChar) {
        String charStr = String.valueOf(paddingChar);
        return getMaskString(origin, prefixLength, paddingLength, suffixLength, charStr);
    }

    @NotNull
    public static String getMaskString(@Nullable String origin, int prefixLength, int paddingLength,
                                       int suffixLength) {
        return getMaskString(origin, prefixLength, paddingLength, suffixLength, "*");
    }

}
